<template>
    <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error="error"
    error-text="加载失败，请点击重试"
    :immediate-check="false"
    @load="onLoad"> <!-- 关闭初始检查 -->
        <CommentItem
        v-for="(item, index) in list" :key="index"
        :comment="item"
        @replyClick="$emit('replyClick', $event)"/>
    </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'

export default {
    name: 'CommentList',
    props: {
        list: {
            type: Array,
            default: () => []
        },
        type: {
            type: String,
            default: 'a'
        },
        source: {
            type: [Number, String, Object],
            required: true
        }
    },
    components: {
        CommentItem
    },
    data () {
        return {
            // list: [],
            loading: false,
            finished: false,
            offset: null, // 获取下一页数据的标记
            error: false
        }
    },
    methods: {
        async onLoad () {
            try {
                const res = await getComments({
                    type: this.type, // 评论类型： a，对文章的评论；c，对评论的恢复
                    source: this.source, // 文章id或评论id
                    offset: this.offset, // 评论数据的偏移量，值为评论id
                    limit: 10 // 获取的评论数据个数
                })
                console.log(res)

                const { results } = res.data.data

                // 把评论数量传递到父组件
                this.$emit('onLoadSuccess', res.data.data)

                this.list.push(...results)
                this.loading = false

                // 当结果为空时，表示列表已经加载完成，没有更多数据了
                if (results.length) {
                    this.offset = res.data.data.last_id
                } else {
                    this.finished = true
                }
            } catch (err) {
                this.error = true
                this.loading = false
            }
        }
    },
    created () {
        this.loading = true
        this.onLoad()
    }
}
</script>
